package com.jtbd.handler;

import com.jtbd.client.JtbdRedisClient;
import com.jtbd.config.CustomAuthentication;
import com.jtbd.dto.JwtPayloadEntity;
import com.jtbd.dto.UserAuthDetailsEntity;
import com.jtbd.utils.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collection;

@Component
public class JudgeTokenIsInvalidHandlerImpl implements JudgeTokenIsInvalidHandler {
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private JtbdRedisClient redisClient;

    /**
     * 判断token是否无效
     *
     * @param token 待验证的JWT token字符串
     * @return true表示token无效，false表示token有效
     */
    @Override
    public boolean judgeTokenIsInvalid(String token) {
        // 验证token格式是否有效
        if (!jwtUtil.validateToken(token)) {
            return true;
        }

        // 从token中提取负载信息
        JwtPayloadEntity realInfoFromJwt = jwtUtil.getRealInfoFromJwt(token);
        if (realInfoFromJwt == null) {
            return true;
        }

        // 从redis中获取存储的token签名字符，并与当前token的签名字符进行比对
        String redisTokenSignChar = redisClient.get(JwtUtil.redisTokenKey(String.valueOf(realInfoFromJwt.getId())));
        return ObjectUtils.isEmpty(redisTokenSignChar) || !redisTokenSignChar.equals(realInfoFromJwt.getSignChar());
    }

    @Override
    public UsernamePasswordAuthenticationToken getAuthentication(String token) {
        // 从token中提取负载信息
        JwtPayloadEntity realInfoFromJwt = jwtUtil.getRealInfoFromJwt(token);
        if (!ObjectUtils.isEmpty(realInfoFromJwt)) {
            UserAuthDetailsEntity userAuthDetailsEntity = new UserAuthDetailsEntity();
            userAuthDetailsEntity.setUid(realInfoFromJwt.getId());
            String[] usernameArr = CustomAuthentication.splitUsername(realInfoFromJwt.getUsername());
            if (!ObjectUtils.isEmpty(usernameArr) && usernameArr.length == 2) {
                String phone = usernameArr[0];
                Integer userType = Integer.parseInt(usernameArr[1]);
                userAuthDetailsEntity.setPhone(phone);
                userAuthDetailsEntity.setUserType(userType);
            }
            userAuthDetailsEntity.setPassword(realInfoFromJwt.getPassword());
            userAuthDetailsEntity.setRoleIds(realInfoFromJwt.getRole());
            return new CustomAuthentication(userAuthDetailsEntity, null);
        }
        return null;
    }
}
